from django.db import models
from system.models import UserProfile


class Organization(models.Model):
    class Meta:
        db_table = 'tree_orgs'

    name = models.CharField(max_length=48)  # 约束：同一个父节点下名称不能重复
    is_deleted = models.BooleanField(default=False)  # 逻辑删除
    parent = models.ForeignKey(
        'self', on_delete=models.PROTECT,  # self表示自关联外键
        null=True,  # 第一级节点的父id为null，自增字段值不能为0
        verbose_name="父id"  # 使用parent_id自关联实现层级结构
    )  # 字段生成为parent_id

    def __str__(self):
        return f"<Org {self.pk}:{self.name} -> {self.parent_id}>"


class Host(models.Model):
    class Meta:
        db_table = 'tree_hosts'

    org = models.ForeignKey(Organization, on_delete=models.PROTECT, related_name="hosts")  # 组id
    ip = models.GenericIPAddressField(null=False, verbose_name="被管理主机的IP")
    username = models.CharField(max_length=48, verbose_name='用户名')
    password = models.CharField(null=True, blank=True, max_length=48, verbose_name='密码')
    ssh_pkey_path = models.CharField(null=True, blank=True, max_length=250, verbose_name='私钥文件路径')
    is_deleted = models.BooleanField(default=False)


class Track(models.Model):
    class OPTYPES(models.IntegerChoices):
        LOGIN = (1, '登录')
        LOGOUT = (2, '登出')
        COMMAND = (3, '命令')

    class Meta:
        db_table = "tree_tracks"
        ordering = ["-op_date"]  # 按日期降序

    user = models.ForeignKey(UserProfile, models.PROTECT, db_column="user_id")
    host = models.ForeignKey(Host, models.PROTECT, db_column='host_id')
    source_ip = models.GenericIPAddressField()
    op_type = models.IntegerField(choices=OPTYPES.choices)
    # op_date = models.DateTimeField(auto_now_add=True)
    op_date = models.DateTimeField()
    command = models.CharField(null=True, blank=True, max_length=250, verbose_name="历史命令")
    op_result = models.TextField(verbose_name="执行结果")
